package com.zhs.study.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author zhenghuisheng
 * @date : 2022/11/4
 */
public class HttpClientUtil {

    /**
     * get请求
     * @param url ： 需要请求的路径
     * @param headerTokenName ： 请求头中token的名字
     * @param headerTokenValue ： 请求头中token的值
     * @param map ： 需要的参数
     * @return
     */
    public static String getMessage(String url, String headerTokenName,String headerTokenValue,Map<String, Object> map) {
        //获取到 客户端 对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //设置参数
        if (!CollectionUtils.isEmpty(map)){
            //添加参数
            StringBuilder param = addParamByGet(map);
            //拼接参数
            url = url + "?" + param;
        }
        HttpGet httpGet = new HttpGet(url);
        //响应
        CloseableHttpResponse response;
        try {
            //设置Content-Type
            httpGet.setHeader("Content-Type","application/json");
            //设置token
            if (StringUtils.isEmpty(headerTokenName)){
                httpGet.addHeader(headerTokenName, headerTokenValue);
            }
            //添加请求配置，设置响应时间等
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000) //服务器响应超时时间
                    .setConnectionRequestTimeout(2000) //连接服务器超时时间
                    .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                    .build();
            //将配置信息添加到 httpGet 中
            httpGet.setConfig(requestConfig);
            //获取响应结果
            response = httpClient.execute(httpGet);
            //封装成实体类
            HttpEntity entity = response.getEntity();
            //将内容转化为字符串，并且设定指定字符集
            //返回执行结果
            return EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源释放
            try {
                httpGet.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * post请求
     */
    public static String postMessage(String url, String headerTokenName,String headerTokenValue, Map<String, Object> map) throws IOException {
        //构建客户端对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            /* 创建http post请求对象 */
            HttpPost post = new HttpPost(url);
            //设置请求头
            post.setHeader(headerTokenName, headerTokenValue);
            post.setHeader("Content-Type","application/json");
            //构建参数
            if (!CollectionUtils.isEmpty(map)){
                JSONObject jo = new JSONObject();
                //增加参数
                addParam(map,jo);
                post.setEntity(new StringEntity(jo.toString(), ContentType.APPLICATION_JSON));
            }else {
                post.setEntity(new StringEntity(null, ContentType.APPLICATION_JSON));
            }
            //创建响应对象
            response = httpClient.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            response.close();
            httpClient.close();
        }
        return null;
    }

    /**
     * get添加参数
     */
    public static StringBuilder addParamByGet(Map<String,Object> map){
        StringBuilder param = new StringBuilder();
        //遍历参数
        for (Map.Entry<String, Object> m :map.entrySet()) {
            param.append(m.getKey()).append("=").append(m.getValue()).append("&");
        }
        return param;
    }

    /**
     * post添加参数
     */
    public static void addParam(Map<String, Object> map, JSONObject jsonObject){
        jsonObject.putAll(map);
    }

}
